package com.alferd.mall.mq.listener;

import com.alferd.mall.mq.cache.GoodsRedisStoreCache;
import com.alferd.mall.mq.cache.SeckillFinishCache;
import com.alferd.mall.mq.cache.SeckillSuccessTokenCache;
import com.alfred.mall.mq.api.dto.MiaoshaMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SeckillMsgMqListener {

    @Autowired
    private SeckillFinishCache seckillFinishCache;
    @Autowired
    private GoodsRedisStoreCache goodsRedisStoreCache;
    @Autowired
    private SeckillSuccessTokenCache seckillSuccessTokenCache;

    @RabbitListener(queues = "${user.miaosha.queue.name}", containerFactory = "singleListenerContainer")
    public void consumerMessage(@Payload MiaoshaMessageDTO miaoshaMessageDTO) {
        //1、先看抢购是否已经结束了，秒杀结束会在redis打标
        if (seckillFinishCache.isFinish(miaoshaMessageDTO.getGoodsRandomName())) {
            log.info("抱歉，您来晚了，抢购已经结束了");
            return;
        }
        //2、扣减redis库存
        if (goodsRedisStoreCache.decrStore(miaoshaMessageDTO.getGoodsRandomName())) {
            return;
        }
        //3、扣减redis库存成功，生成下单token供页面真正下单使用
        seckillSuccessTokenCache.createToken(miaoshaMessageDTO);


        log.info("队列消费掉 {}", miaoshaMessageDTO);
    }
}
